<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ishowshao
 * Date: 12-12-11
 * Time: 下午9:15
 * To change this template use File | Settings | File Templates.
 */
require 'config.php';
session_start();
if (empty($_SESSION['username'])) {
    exit;
} else {
    $username = $_SESSION['username'];
}

if (isset($_POST['time'])) {
    $time = intval($_POST['time']);
} else {
    exit;
}
if (isset($_POST['comment'])) {
    $comment = trim($_POST['comment']);
} else {
    exit;
}

$output = array('success' => false, 'data' => '', 'msg' => '');
//输入检查
//检查回复内容
if ($comment === '') {
    echo json_encode($output);
    exit;
}
//检查time是否合法
if ($time == 0) {
    echo json_encode($output);
}
$data = json_decode(file_get_contents(DATA_FILE), true);

$hasTime = false;
$hasTimeKey = false;
foreach ($data as $key => $item) {
    if ($item['time'] == $time) {
        $hasTime = $item;
        $hasTimeKey = $key;
        break;
    }
}
if (!$hasTime) {
    echo json_encode($output);
    exit;
}

date_default_timezone_set('PRC');
$comment = array(
    'time' => time(),
    'user' => $username,
    'content' => $comment,
);

if (!is_array($data[$hasTimeKey]['comments'])) {
    $data[$hasTimeKey]['comments'] = array();
}
array_push($data[$hasTimeKey]['comments'], $comment);

file_put_contents(DATA_FILE, json_encode($data));

$output['success'] = true;
$output['data'] = $comment;
echo json_encode($output);
